<template>
  <div class="service-list">
    <div class="page-header">
      <h2>家政服务管理</h2>
      <el-button type="primary" @click="showAddDialog = true">
        <el-icon><Plus /></el-icon>
        添加服务
      </el-button>
    </div>
    
    
    <div class="filters">
      <el-select v-model="categoryFilter" placeholder="按分类筛选" clearable @change="loadServices">
        <el-option
          v-for="category in categories"
          :key="category.categoryId"
          :label="category.categoryName"
          :value="category.categoryId"
        />
      </el-select>
      <el-input v-model="searchKeyword" placeholder="搜索服务名称" style="width: 200px;" @keyup.enter="searchServices" />
      <el-button @click="searchServices">搜索</el-button>
      <el-button @click="resetSearch">重置</el-button>
    </div>
    
    <el-table :data="services" style="width: 100%" v-loading="loading">
      <el-table-column prop="serviceId" label="服务ID" width="100" />
      <el-table-column prop="serviceName" label="服务名称" />
      <el-table-column prop="categoryName" label="服务分类" width="120" />
      <el-table-column prop="price" label="价格" width="100">
        <template #default="scope">
          ¥{{ scope.row.price }}
        </template>
      </el-table-column>
      <el-table-column prop="unit" label="单位" width="80" />
      <el-table-column prop="serviceTime" label="服务时长" width="100" />
      <el-table-column label="状态" width="100">
        <template #default="scope">
          <el-tag v-if="scope.row.status === 1" type="success">可用</el-tag>
          <el-tag v-else type="danger">禁用</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="320">
        <template #default="scope">
          <el-button size="small" @click="viewService(scope.row)">查看</el-button>
          <el-button size="small" type="primary" @click="editService(scope.row)">编辑</el-button>
          <el-button size="small" type="info" @click="viewServiceReviews(scope.row)">评价</el-button>
          <el-button v-if="scope.row.status === 1" size="small" type="warning" @click="toggleStatus(scope.row.serviceId, 0)">禁用</el-button>
          <el-button v-else size="small" type="success" @click="toggleStatus(scope.row.serviceId, 1)">启用</el-button>
          <el-button size="small" type="danger" @click="deleteService(scope.row.serviceId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    
    <el-dialog v-model="showDetailDialog" title="服务详情" width="600px">
      <div v-if="selectedService">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="服务名称">{{ selectedService.serviceName }}</el-descriptions-item>
          <el-descriptions-item label="服务分类">{{ selectedService.categoryName }}</el-descriptions-item>
          <el-descriptions-item label="价格">¥{{ selectedService.price }}</el-descriptions-item>
          <el-descriptions-item label="单位">{{ selectedService.unit }}</el-descriptions-item>
          <el-descriptions-item label="服务时长">{{ selectedService.serviceTime }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag v-if="selectedService.status === 1" type="success">可用</el-tag>
            <el-tag v-else type="danger">禁用</el-tag>
          </el-descriptions-item>
        </el-descriptions>
        <div style="margin-top: 20px;">
          <h4>服务描述：</h4>
          <p>{{ selectedService.description || '暂无描述' }}</p>
        </div>
      </div>
    </el-dialog>
    
    
    <el-dialog v-model="showAddDialog" :title="isEdit ? '编辑服务' : '添加服务'" width="600px">
      <el-form :model="serviceForm" label-width="100px" :rules="serviceRules" ref="serviceFormRef">
        <el-form-item label="服务名称" prop="serviceName">
          <el-input v-model="serviceForm.serviceName" />
        </el-form-item>
        <el-form-item label="服务分类" prop="categoryId">
          <el-select v-model="serviceForm.categoryId" placeholder="请选择分类">
            <el-option
              v-for="category in categories"
              :key="category.categoryId"
              :label="category.categoryName"
              :value="category.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="serviceForm.price" :min="0" :precision="2" />
        </el-form-item>
        <el-form-item label="单位" prop="unit">
          <el-input v-model="serviceForm.unit" placeholder="如：小时、次、平方米" />
        </el-form-item>
        <el-form-item label="服务时长" prop="serviceTime">
          <el-input v-model="serviceForm.serviceTime" placeholder="如：2小时、1天" />
        </el-form-item>
        <el-form-item label="服务描述">
          <el-input v-model="serviceForm.description" type="textarea" rows="4" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="cancelForm">取消</el-button>
        <el-button type="primary" @click="submitForm">{{ isEdit ? '更新' : '添加' }}</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api'
import { ElMessage, ElMessageBox } from 'element-plus'

export default {
  name: 'ServiceList',
  data() {
    return {
      services: [],
      categories: [],
      loading: false,
      categoryFilter: null,
      searchKeyword: '',
      showDetailDialog: false,
      showAddDialog: false,
      selectedService: null,
      isEdit: false,
      serviceForm: {
        serviceId: null,
        serviceName: '',
        categoryId: null,
        price: 0,
        unit: '',
        serviceTime: '',
        description: ''
      },
      serviceRules: {
        serviceName: [
          { required: true, message: '请输入服务名称', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择服务分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入价格', trigger: 'blur' }
        ],
        unit: [
          { required: true, message: '请输入单位', trigger: 'blur' }
        ],
        serviceTime: [
          { required: true, message: '请输入服务时长', trigger: 'blur' }
        ]
      }
    }
  },
  mounted() {
    this.loadServices()
    this.loadCategories()
  },
  methods: {
    async loadServices() {
      this.loading = true
      try {
        let url = '/api/services'
        if (this.categoryFilter) {
          url += `?categoryId=${this.categoryFilter}`
        }
        
        const response = await api.get(url)
        if (response.success) {
          this.services = response.data
        } else {
          ElMessage.error('加载服务列表失败')
        }
      } catch (error) {
        console.error('加载服务失败:', error)
        ElMessage.error('加载服务列表失败')
      } finally {
        this.loading = false
      }
    },
    
    async loadCategories() {
      try {
        const response = await api.get('/api/services/categories')
        if (response.success) {
          this.categories = response.data
        }
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    },
    
    async searchServices() {
      if (!this.searchKeyword.trim()) {
        this.loadServices()
        return
      }
      
      this.loading = true
      try {
        const response = await api.get(`/api/services/search?keyword=${this.searchKeyword}`)
        if (response.success) {
          this.services = response.data
        } else {
          ElMessage.error('搜索失败')
        }
      } catch (error) {
        console.error('搜索失败:', error)
        ElMessage.error('搜索失败')
      } finally {
        this.loading = false
      }
    },
    
    resetSearch() {
      this.searchKeyword = ''
      this.categoryFilter = null
      this.loadServices()
    },
    
    viewService(service) {
      this.selectedService = service
      this.showDetailDialog = true
    },
    
    viewServiceReviews(service) {

      this.$router.push({
        path: '/reviews',
        query: { serviceId: service.serviceId, serviceName: service.serviceName }
      })
    },
    
    editService(service) {
      this.isEdit = true
      this.serviceForm = { ...service }
      this.showAddDialog = true
    },
    
    async toggleStatus(serviceId, status) {
      try {
        const action = status === 1 ? '启用' : '禁用'
        await ElMessageBox.confirm(`确认${action}此服务？`, '确认操作', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await api.put(`/api/services/${serviceId}/status`, { status })
        if (response.success) {
          ElMessage.success(`服务已${action}`)
          this.loadServices()
        } else {
          ElMessage.error(`${action}服务失败`)
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('状态更新失败:', error)
          ElMessage.error('状态更新失败')
        }
      }
    },
    
    async deleteService(serviceId) {
      try {
        await ElMessageBox.confirm('确认删除此服务？删除后不可恢复', '危险操作', {
          confirmButtonText: '删除',
          cancelButtonText: '取消',
          type: 'error'
        })
        
        const response = await api.delete(`/api/services/${serviceId}`)
        if (response.success) {
          ElMessage.success('服务已删除')
          this.loadServices()
        } else {
          ElMessage.error('删除服务失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除服务失败:', error)
          ElMessage.error('删除服务失败')
        }
      }
    },
    
    async submitForm() {
      try {
        await this.$refs.serviceFormRef.validate()
        
        if (this.isEdit) {
          const response = await api.put(`/api/services/${this.serviceForm.serviceId}`, this.serviceForm)
          if (response.success) {
            ElMessage.success('服务更新成功')
            this.cancelForm()
            this.loadServices()
          } else {
            ElMessage.error('更新服务失败')
          }
        } else {
          const response = await api.post('/api/services', this.serviceForm)
          if (response.success) {
            ElMessage.success('服务添加成功')
            this.cancelForm()
            this.loadServices()
          } else {
            ElMessage.error('添加服务失败')
          }
        }
      } catch (error) {
        if (error.message) {
          console.error('表单验证失败:', error)
          ElMessage.error('请检查表单信息')
        } else {
          console.error('提交失败:', error)
          ElMessage.error('操作失败')
        }
      }
    },
    
    cancelForm() {
      this.showAddDialog = false
      this.isEdit = false
      this.resetForm()
    },
    
    resetForm() {
      this.serviceForm = {
        serviceId: null,
        serviceName: '',
        categoryId: null,
        price: 0,
        unit: '',
        serviceTime: '',
        description: ''
      }
      if (this.$refs.serviceFormRef) {
        this.$refs.serviceFormRef.clearValidate()
      }
    }
  }
}
</script>

<style scoped>
.service-list {
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.filters {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.filters .el-select {
  width: 150px;
}
</style> 